﻿using JinfuyuanProject.Entity;
using JinfuyuanProject.Entity.Filter;
using JinfuyuanProject.Service;
using JinfuyuanProject.Service.Interface;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml.Linq;
using System.Transactions;
using System.Web.Configuration;
using JinfuyuanProject.Entity.ViewModels;
using Newtonsoft.Json;

namespace JinfuyuanProject.Controllers
{
  /*
  * 2025-4-23
  * 房间页面、房间详情、服务购买、产品购买
  * 周梦飞
  */
    public class RoomController : Controller
    {
        private readonly IHomeService _homeService;
        private readonly IPackageService _packageService;
        private readonly IServiceDoService _serviceDoService;
        private readonly IServicesService _servicesService;
        private readonly IProductService _productService;
        private readonly IContractService _contractService;
        private readonly IExpenseRecordService _expenseRecordService;
        private readonly JinfuyuanDbContext _dbContext;
        private readonly IProductApplicationService _productApplication;

        public RoomController(IHomeService homeService, IPackageService packageService,IServiceDoService serviceDoService,IServicesService servicesService,IProductService productService, IContractService contractService,IExpenseRecordService expenseRecordService, JinfuyuanDbContext db,IProductApplicationService productApplication)
        {
            _homeService = homeService;
            _packageService = packageService;
            _serviceDoService= serviceDoService;
            _servicesService= servicesService;
            _productService= productService;
            _contractService= contractService;
            _expenseRecordService= expenseRecordService;
            _dbContext= db;
            _productApplication= productApplication;
        }
        // GET: House
        #region 页面
        public ActionResult Room()
        {
            var packages = _packageService.GetList()?.ToList() ?? new List<Package>();
            var json = JsonConvert.SerializeObject(packages, new JsonSerializerSettings
            {
                StringEscapeHandling = StringEscapeHandling.EscapeHtml // 转义HTML特殊字符
            });
            ViewBag.Package = json;
            ViewBag.HomeVM = _homeService.GetRoomDetail();
            return View();
        }
        public ActionResult RoomDetail(int id)
        {
            Home home = _homeService.GetModel(id);
            if (home.State == 0)
            {
                //未入住
                ViewBag.RoomDetail = null;
                ViewBag.HomeVM = _homeService.GetRoomDetail().Where(h => h.Id == id).FirstOrDefault();
            }
            else
            {
                //已入住
                var parturientvm = _homeService.GetParturientVM(id);
                if (parturientvm.LiveTime.HasValue)
                {
                    parturientvm.DaysStayed = (DateTime.Now - parturientvm.LiveTime.Value).Days;
                    if (parturientvm.DaysStayed == 0)  //再今天入住显示入住1天而不是显示入住0天
                    {
                        parturientvm.DaysStayed++;
                    }
                }
                else
                {
                    parturientvm.DaysStayed = 0;
                }
                ViewBag.RoomDetail = parturientvm;
                int ParturientId= parturientvm.Id;
                //得到宝宝信息
                ViewBag.Baby = _homeService.GetBabyDetail(id);
                //得到服务信息
                var servicevm = _homeService.GetServiceDoVM(ParturientId);
                ViewBag.TodyService = servicevm.Where(s => s.ServiceTime.HasValue&& s.ServiceTime.Value.Date == DateTime.Today);
                ViewBag.HistoryService = servicevm.Where(s => s.ServiceTime.HasValue&& s.ServiceTime.Value.Date < DateTime.Today);
            }
            return View();
        }
        public ActionResult BuyService(int id)
        {
            ViewBag.Service = _servicesService.GetList();
            ViewBag.ContractId = id;
            return View();
        }
        public ActionResult BuyProduct(int id)
        {
            ViewBag.ContractId = id;
            return View();
        }

        public ActionResult EditRoom(int Id)
        {
            ViewBag.HomeId = Id;
            ViewBag.Package = _packageService.GetList();
            var homes = _homeService.GetList();
            int maxFloor = homes.Max(h => h.Floors);
            ViewBag.floor=maxFloor;
            return View();
        }
        #endregion

        #region 接口
        //提交服务反馈
        [HttpPost]
        public JsonResult SubmitFeedBack(int Id,string feedback)
        {
            Hashtable hs = new Hashtable();
            ServiceDo serviceDo=_serviceDoService.GetModel(Id);
            if (serviceDo == null)
            {
                hs["code"] = 1;
                hs["data"]=null;
                return Json(hs);
            }
            serviceDo.FeedBack = feedback;
            _serviceDoService.Update(serviceDo);
            hs["code"] = 0;
            hs["data"]=serviceDo.FeedBack;
            return Json(hs);
        }
        //根据id得到一个服务实体
        [HttpPost]
        public JsonResult GetService(int id)
        {
            Services service=_servicesService.GetModel(id);
            Hashtable hs = new Hashtable();
            if (service == null)
            {
                hs["code"] = 1;
                hs["data"] = null;
                return Json(hs);
            }
            hs["code"] = 0;
            hs["data"] = service;
            return Json(hs);
        }
        //产品列表API
        public JsonResult ProductAPI(int page, int limit, string ProductName)
        {
            ProductFilter filter = new ProductFilter();
            filter.ProductName = ProductName;
            filter.page = page;
            filter.limit = limit;
            filter.IsDelete = 0;
            return Json(_homeService.ProductAPI(filter), JsonRequestBehavior.AllowGet);
        }
        //判断服务是否超出阈值
        [HttpPost]
        public JsonResult Service(int Id,DateTime value)
        {
            Hashtable hs = new Hashtable();
            // 2. 检查时间是否合法
            if (value.Date < DateTime.Today)
            {
                hs["code"] = 2;
                hs["message"] = "服务时间不能早于今天";
                return Json(hs);
            }
            IQueryable<ServiceDo> serviceDo=_serviceDoService.GetList().Where(s => s.Sid == Id && DbFunctions.TruncateTime(s.ServiceTime.Value) == DbFunctions.TruncateTime(value));
            int count=serviceDo.Count();
            Services service = _servicesService.GetList().Where(s => s.Id == Id).FirstOrDefault();
            if (count < service.ServiceThreshold)
            {
                hs["code"] = 0;
                hs["message"] = "该时间段可用";
            }
            else
            {
                hs["code"] = 1;
                hs["message"] = "该时间段已满";
            }
            return Json(hs);
        }
        //购买服务
        [HttpPost]
        public JsonResult PurchaseService(string productData)
        {
            productData = HttpUtility.UrlDecode(productData);
            BuyServiceVM buyServiceVM = Newtonsoft.Json.JsonConvert.DeserializeObject<BuyServiceVM>(productData);
            Hashtable hs = new Hashtable();
            //得到合同id
            int ContractId = buyServiceVM.ContractId;
            //根据合同id得到相应的数据
            Contract contract=_contractService.GetModel(ContractId);
            contract.Deposit -= buyServiceVM.price; // 扣除押金
           // 实例化一个消费记录实体
            ExpenseRecord expenseRecord = new ExpenseRecord();
            expenseRecord.Type = 2;
            expenseRecord.ConsId = buyServiceVM.service;
            expenseRecord.ConsCount = 1;
            expenseRecord.Price = buyServiceVM.price;
            expenseRecord.Cid = ContractId;
            expenseRecord.ApplyId = contract.ParturientId;
            expenseRecord.IsDelete = 0;
            expenseRecord.CreateTime = DateTime.Now;
            expenseRecord.Balance = contract.Deposit;
            //消费记录表的余额
            //实例化一个服务任务实体
            ServiceDo serviceDo=new ServiceDo();
            serviceDo.Cid= ContractId;
            serviceDo.Sid = buyServiceVM.service;
            serviceDo.ServiceTime=buyServiceVM.date;
            serviceDo.IsDelete=0;
            serviceDo.CreateTime = DateTime.Now;
            
            //创建一个事务,一次性进行更新合同表里押金的金额，插入一条消费记录，插入一条服务任务
            using (var dbContextTransaction = _dbContext.Database.BeginTransaction())
            {
                try
                {
                    // 更新合同押金金额
                    _dbContext.Entry(contract).State=EntityState.Modified;
                    // 插入消费记录
                    _dbContext.Entry(expenseRecord).State = EntityState.Added;
                    // 插入服务任务
                    _dbContext.Entry(serviceDo).State = EntityState.Added;
                    // 提交事务
                    dbContextTransaction.Commit();
                    _dbContext.SaveChanges();
                    hs["code"] = 0;
                    hs["msg"] = "购买成功";
                }
                catch (Exception ex)
                {
                    // 事务回滚
                    dbContextTransaction.Rollback();
                    hs["code"] = 2;
                    hs["msg"] = "购买失败：" + ex.Message;
                }
            }
            return Json(hs);
        }

        [HttpPost]
        public JsonResult PruchaseProduct(string productData)
        {
            productData = HttpUtility.UrlDecode(productData);
            BuyProductVM buyProductVM = Newtonsoft.Json.JsonConvert.DeserializeObject<BuyProductVM>(productData);
            int Id=((Staff)HttpContext.Session["user"]).Id;
            Hashtable hs = new Hashtable();
            //得到合同id
            int ContractId = buyProductVM.ContractId;
            //根据合同id得到相应的数据
            Contract contract = _contractService.GetModel(ContractId);
            //contract.Deposit -= buyProductVM.TotalAmount; // 扣除押金(套餐金额不变)
            foreach (var Product in buyProductVM.Products)
            {
                //考虑商品阀值是否触发
                Product product = _productService.GetModel(Product.ProductId);
                if (Product.Quantity>product.Threshold) //如果购买的商品的数量大于这个商品的阈值
                {
                    hs["code"] = 1;
                    hs["msg"] = "商品库存不足";
                    return Json(hs);
                }
                else
                {
                    //减少相应的库存数量
                    product.Number-=Product.Quantity;
                    //实例化一个消费记录实体
                    //ExpenseRecord expenseRecord = new ExpenseRecord();
                    //expenseRecord.Type = 1;
                    //expenseRecord.ConsId = Product.ProductId;
                    //expenseRecord.ConsCount = Product.Quantity;
                    //expenseRecord.Price = Product.Price;
                    //expenseRecord.Cid = ContractId;
                    //expenseRecord.ApplyId = contract.ParturientId;
                    //expenseRecord.IsDelete = 0;
                    //expenseRecord.CreateTime = DateTime.Now;
                    //实例化一个商品申请实体
                    ProductApplication productApplication = new ProductApplication();
                    productApplication.ContractId = ContractId;
                    productApplication.ApplicationId = Id;
                    productApplication.ProductId = Product.ProductId;
                    productApplication.Number = Product.Quantity;
                    productApplication.IsDelete = 0;
                    productApplication.CreateTime = DateTime.Now;
                    //添加出库记录
                    Inbound inbound = new Inbound();
                    inbound.ProductId = Product.ProductId;
                    inbound.Number = Product.Quantity;
                    inbound.InboundId=Id;
                    inbound.InboundTime = DateTime.Now;
                    inbound.CreateTime = DateTime.Now;
                    inbound.IsDelete = 0;
                    inbound.Type = 0;
                    //创建一个事务,一次性进行更新合同表里押金的金额，插入一条消费记录，插入一条服务任务
                    using (var dbContextTransaction = _dbContext.Database.BeginTransaction())
                    {
                        try
                        {
                            //更新商品表
                            _dbContext.Entry(product).State = EntityState.Modified;
                            if (product.Number <= product.Threshold)
                            {
                                MessageInfo messageInfo = new MessageInfo()
                                {
                                    Contents = $"请去进{product.Id}号商品",
                                    StaffRecId = 1,
                                    StaffSendId = 0,
                                    CreateTime = DateTime.Now,
                                    IsDelete = 0,
                                    Href = "/Product/ProductList",
                                    IsRead = 0,
                                    Times = DateTime.Now
                                };
                                _dbContext.Entry(messageInfo).State = EntityState.Added;
                            }
                            //插入商品申请表
                            _dbContext.Entry(productApplication).State = EntityState.Added;
                            _dbContext.SaveChanges();
                            inbound.ApplicationId = productApplication.Id;
                            // 更新合同押金金额
                            //_dbContext.Entry(contract).State = EntityState.Modified;
                            // 插入消费记录
                            //_dbContext.Entry(expenseRecord).State = EntityState.Added;
                            //插入出库记录
                            _dbContext.Entry(inbound).State = EntityState.Added;
                            // 提交事务
                            dbContextTransaction.Commit();
                            _dbContext.SaveChanges();
                            hs["code"] = 0;
                            hs["msg"] = "购买成功";
                        }
                        catch (Exception ex)
                        {
                            // 事务回滚
                            dbContextTransaction.Rollback();
                            hs["code"] = 2;
                            hs["msg"] = "购买失败：" + ex.Message;
                        }
                    }
                }
            }
            return Json(hs);
        }
        //添加房间信息
        [HttpPost]
        public JsonResult AddRoom(RoomVM roomVM)
        {
            Hashtable hs = new Hashtable();
            //实例化一个home实体
            Home home = new Home();
            home.Name=roomVM.Name;
            home.Floors=roomVM.Floors;
            home.Area=roomVM.Area;
            home.PackageId=roomVM.PackageId;
            home.State = 0;
            home.Direction = roomVM.Direction;
            home.IsDelete = 0;
            home.CreateTime=DateTime.Now;
            //将房间插入房间表
            _homeService.Insert(home);
            hs["code"] = 0;
            return Json(hs);
        }
        //绑定房间信息
        [HttpPost]
        public JsonResult GetRoom(int id)
        {
            Hashtable hs = new Hashtable();
            hs["code"] = 0;
            hs["data"]=_homeService.GetModel(id);
            return Json(hs);
        }
        //编辑房间信息
        [HttpPost]
        public JsonResult EditRoom(RoomVM roomVM)
        {
            Hashtable hs = new Hashtable();
            Home home = _homeService.GetModel(roomVM.Id);
            home.Name=roomVM.Name;
            home.Floors = roomVM.Floors;
            home.Area=roomVM.Area;  
            home.PackageId = roomVM.PackageId;
            home.Direction = roomVM.Direction;
            _homeService.Update(home);
            hs["code"] = 0;
            return Json(hs);
        }

        #endregion
    }
}